/*
 * @LastEditors: 张功睿
 */

var i18n;
var apiUrl = 'http://demo.sfddgv.com/index.php';
var apiUrl1 = 'http://demo.sfddgv.com';
/* var apiUrl1 = 'http://ysmc.xiaoxiongkeji.cn/index.php/index/index/login'; */

// var apiUrl = 'http://chaojiyinliu.gzmc668.com/';
// var apiUrl1 = 'http://chaojiyinliu.gzmc668.com/index.php/index/index/login';
function setFont($designs) { //移动端rem适配  参数传入设计稿宽度
	var des = $designs / 100;
	document.documentElement.style.fontSize = document.documentElement.clientWidth / des + "px";
	document.getElementsByTagName('body')[0].style.fontSize = '16px';
}
//存touken
function is_login() {
	var uid = $api.getStorage('token');
	if (!uid || uid == "") {
		// openWebWin({
		//     url: shopUrl + 'mobile/user.php',
		//     title: '登录',
		// });
		return false;
	} else {
		return true;
	}
	return true;
}
/**
 * 保存图片到相册
 * @param array 当前图片数组
 * @return string
 */
function save_img(array) {
	api.actionSheet({
		cancelTitle: '取消',
		buttons: ['保存到相册']
	}, function(ret, err) {
		var index = ret.buttonIndex;
		if (index == 1) {
			var photoBrowser = api.require('photoBrowser');
			photoBrowser.getIndex(function(ret, err) {
				if (ret) {
					api.download({
						url: array[ret.index],
						savePath: 'fs://Camera/' + new Date().getTime() + '.png',
						report: true,
						cache: true,
						allowResume: true
					}, function(result, err) {
						if (result.state == 1) {
							api.saveMediaToAlbum({
								path: result.savePath,
								groupName: 'fs://',
							}, function(ret, err) {
								if (ret && ret.status) {
									alert('图片保存成功');
								} else {
									alert('图片保存失败');
								}
							});
						}
					});
				}
			});
		}
	});
}
//选择拍照或者选择相册并完成相应的请求权限-质量压缩-----------------------------------------------------------------------------------------------------------------
// function choose_methods($maxLength,$nowLength,images=[],callBack){
function choose_methods($maxLength, $nowLength, images, callBack) {
	//判断当前图片数量是否大于等于最大图片数量
	if ($nowLength >= $maxLength) {
		ApiAlert("图片限制", "当前图片数量已达到最大可以上传数量，请删除图片后再选择！", function() {});
		return;
	}
	api.actionSheet({
		cancelTitle: '取消',
		buttons: ['打开相机', '系统相册']
	}, function(ret, err) {
		var thumbnailUtil = api.require('thumbnailUtil');
		var index = ret.buttonIndex;
		if (index == 1) {
			var result = hasPermission('camera'); //权限检测
			var text = '"趣引流"需要使用相机功能,请设置相机权限,点击确定前往设置相机权限,点击取消拒绝';
			requestPermission(text, 'camera', result, function(bool) {
				if (bool) {
					//单图选择
					getPicture1(function(imgUrl) {
						//回调返回用户拍照的图片
						if (api.systemType == 'ios') {
							var index = imgUrl.lastIndexOf(".");
							var ext = imgUrl.substr(index + 1).toLowerCase();
							if (ext == 'jpeg') {
								ext = 'jpg';
							}
							if (ext !== 'jpg') {
								msg('图片格式不对');
								api.hideProgress();
								return;
							}
							var imageFilter = api.require('imageFilter');
							imageFilter.getAttr({
								path: imgUrl,
							}, function(rets, err) {
								if (rets.status) {
									if (rets.width != 525) {
										msg("图片大小不合格");
										return;
									}
									if (rets.height != 265) {
										msg("图片大小不合格");
										return;
									}
									var timestamp = (new Date()).getTime();
									var demo = api.require('imageOptim');
									demo.compress({
										quality: 1.0,
										width: rets.width,
										height: rets.height,
										imgPath: imgs[i],
										destinationPath: 'fs://' + timestamp + '.png'
									}, function(ret, err) {
										if (ret) {
											images.push(ret.imgPath);
										} else {
											api.alert({
												title: '提示',
												msg: err.message,
											}, function(ret, err) {

											});
										}
									});
								}
							});
						} else {
							var index = imgUrl.lastIndexOf(".");
							var ext = imgUrl.substr(index + 1).toLowerCase();
							if (ext == 'jpeg') {
								ext = 'jpg';
							}
							if (ext !== 'jpg') {
								msg('图片格式不对');
								api.hideProgress();
								return;
							}
							var imageFilter = api.require('imageFilter');
							imageFilter.getAttr({
								path: imgUrl,
							}, function(rets, err) {
								if (rets.status) {
									if (rets.width != 525) {
										msg("图片大小不合格");
										return;
									}
									if (rets.height != 265) {
										msg("图片大小不合格");
										return;
									}
									var timestamp = (new Date()).getTime();
									var demo = api.require('imageOptim');
									demo.compress({
										quality: 1.0,
										width: rets.width,
										height: rets.height,
										imgPath: imgs[i],
										destinationPath: 'fs://' + timestamp + '.png'
									}, function(ret, err) {
										if (ret) {
											images.push(ret.imgPath);
										} else {
											api.alert({
												title: '提示',
												msg: err.message,
											}, function(ret, err) {

											});
										}
									});
								}
							});
						}
						// callBack(images);
					});
				} else {
					msg("获取相机权限失败!无法打开相机");
				}
			});
		} else if (index == 2) {
			if (api.systemType == "ios") {
				api.showProgress({
					title: '努力压缩中...',
					text: '先喝杯茶...',
					modal: false
				});
				var result = hasPermission('photos'); //权限检测
				var text = '"趣引流"需要使用相册功能,请设置相册权限,点击确定前往设置相册权限,点击取消拒绝';
				requestPermission(text, 'photos', result, function(bool) {
					if (bool) {
						//选择相册
						imgs_Browser($maxLength, $nowLength, function(imgs) {
							if (imgs) {
								for (i in imgs) {
									(function(i) {
										var img_url = imgs[i];
										var index = imgs[i].lastIndexOf(".");
										var ext = imgs[i].substr(index + 1).toLowerCase();
										if (ext == 'jpeg') {
											ext = 'jpg';
										}
										if (ext !== 'jpg') {
											msg('图片格式不对');
											api.hideProgress();
											return;
										}
										var imageFilter = api.require('imageFilter');
										imageFilter.getAttr({
											path: img_url,
										}, function(rets, err) {
											if (rets.status) {
												if (rets.width != 525) {
													msg("图片大小不合格");
													api.hideProgress();
													return;
												}
												if (rets.height != 265) {
													msg("图片大小不合格");
													api.hideProgress();
													return;
												}
												var timestamp = (new Date()).getTime();
												var demo = api.require('imageOptim');
												demo.compress({
													quality: 1.0,
													width: rets.width,
													height: rets.height,
													imgPath: imgs[i],
													destinationPath: 'fs://' + timestamp + '.png'
												}, function(ret, err) {
													if (ret) {
														api.hideProgress();
														images.push(ret.imgPath);
													} else {
														api.hideProgress();
														api.alert({
															title: '提示',
															msg: err.message,
														}, function(ret, err) {

														});
													}
												});
											}
										});
									})(i);
								}
							} else {
								api.hideProgress();
							}
						})
					} else {
						msg("获取相册权限失败!无法打开相册");
						api.hideProgress();
					}
				});
			} else {
				var imageFilter = api.require('imageFilter');
				var result = hasPermission('storage'); //权限检测
				var text = '"趣引流"需要使用相册功能,请设置本地存储权限,点击确定前往设置本地存储权限,点击取消拒绝';
				requestPermission(text, 'storage', result, function(bool) {
					if (bool) {
						//选择相册
						imgs_Browser($maxLength, $nowLength, function(imgs) {
							if (imgs) {
								var thumbnailUtil = api.require('thumbnailUtil');
								for (i in imgs) {
									(function(i) {
										var img_url = imgs[i];
										var index = imgs[i].lastIndexOf(".");
										var ext = imgs[i].substr(index + 1).toLowerCase();
										if (ext == 'jpeg') {
											ext = 'jpg';
										}
										if (ext !== 'jpg') {
											msg('图片格式不对');
											api.hideProgress();
											return;
										}
										var imageFilter = api.require('imageFilter');
										imageFilter.getAttr({
											path: img_url,
										}, function(rets, err) {
											if (rets.status) {
												if (rets.width != 525) {
													msg("图片大小不合格");
													return;
												}
												if (rets.height != 265) {
													msg("图片大小不合格");
													return;
												}
												var timestamp = (new Date()).getTime();
												var demo = api.require('imageOptim');
												demo.compress({
													quality: 1.0,
													width: rets.width,
													height: rets.height,
													imgPath: imgs[i],
													destinationPath: 'fs://' + timestamp + '.png'
												}, function(ret, err) {
													if (ret) {
														images.push(ret.imgPath);
													} else {
														api.alert({
															title: '提示',
															msg: err.message,
														}, function(ret, err) {

														});
													}
												});
											}
										});
									})(i);
								}
							} else {
								api.hideProgress();
							}
							// callBack(images);
						})
					} else {
						msg("获取本地储存权限失败!无法打开相册");
						api.hideProgress();
					}
				});
			}

		}
	});
}

//选择拍照或者选择相册并完成相应的请求权限-------------------------------------------------------------------------------------------------------------------
function choose_method($maxLength, $nowLength, images, image, callBack) {
	//判断当前图片数量是否大于等于最大图片数量
	if ($nowLength >= $maxLength) {
		ApiAlert("图片限制", "当前图片数量已达到最大可以上传数量，请删除图片后再选择！", function() {});
		return;
	}
	api.actionSheet({
		cancelTitle: '取消',
		buttons: ['打开相机', '系统相册']
	}, function(ret, err) {
		/* var thumbnailUtil = api.require('thumbnailUtil'); */
		var index = ret.buttonIndex;
		if (index == 1) {
			var result = hasPermission('camera'); //权限检测
			var text = '"趣引流"需要使用相机功能,请设置相机权限,点击确定前往设置相机权限,点击取消拒绝';
			requestPermission(text, 'camera', result, function(bool) {
				if (bool) {
					//单图选择
					getPicture1(function(imgUrl) {
						//回调返回用户拍照的图片
						if (api.systemType == 'ios') {
							var imageFilter = api.require('imageFilter');
							imageFilter.getAttr({
								path: imgUrl,
							}, function(rets, err) {
								if (rets.status) {
									if (rets.width > 800) {
										var widths = 800;
										var heights = 800 / rets.width * rets.height;
										var xwidth = 200;
										var xheight = 200 / rets.width * rets.height;
									} else {
										var widths = rets.width;
										var heights = rets.height;
										var xwidth = 200;
										var xheight = 200 / rets.width * rets.height;
									}
									var timestamp = (new Date()).getTime();
									var demo = api.require('imageOptim');
									demo.compress({
										quality: 0.9,
										width: xwidth,
										height: xheight,
										imgPath: imgUrl,
										destinationPath: 'fs://' + timestamp + '.png'
									}, function(ret, err) {
										if (ret) {
											api.hideProgress();
											image.push(ret.imgPath);
										} else {
											api.hideProgress();
											api.alert({
												title: '提示',
												msg: err.message,
											}, function(ret, err) {

											});
										}
									});
									demo.compress({
										quality: 0.9,
										width: widths,
										height: heights,
										imgPath: imgUrl,
										destinationPath: 'fs://' + timestamp + timestamp + '.png'
									}, function(retss, err) {
										if (retss) {
											api.hideProgress();
											images.push(retss.imgPath);
										} else {
											api.hideProgress();
											api.alert({
												title: '提示',
												msg: err.message,
											}, function(ret, err) {

											});
										}
									});

								}
							});
						} else {
							var imageFilter = api.require('imageFilter');
							imageFilter.getAttr({
								path: imgUrl,
							}, function(rets, err) {
								if (rets.status) {
									if (rets.width > 800) {
										var widths = 800;
										var heights = 800 / rets.width * rets.height;
										var xwidth = 200;
										var xheight = 200 / rets.width * rets.height;
									} else {
										var widths = rets.width;
										var heights = rets.height;
										var xwidth = 200;
										var xheight = 200 / rets.width * rets.height;
									}
									var timestamp = (new Date()).getTime();
									var demo = api.require('imageOptim');
									demo.compress({
										quality: 0.9,
										width: xwidth,
										height: xheight,
										imgPath: imgUrl,
										destinationPath: 'fs://' + timestamp + '.png'
									}, function(ret, err) {
										if (ret) {
											api.hideProgress();
											image.push(ret.imgPath);
										} else {
											api.hideProgress();
											api.alert({
												title: '提示',
												msg: err.message,
											}, function(ret, err) {

											});
										}
									});
									demo.compress({
										quality: 0.9,
										width: widths,
										height: heights,
										imgPath: imgUrl,
										destinationPath: 'fs://' + timestamp + timestamp + '.png'
									}, function(retss, err) {
										if (retss) {
											api.hideProgress();
											images.push(retss.imgPath);
										} else {
											api.hideProgress();
											api.alert({
												title: '提示',
												msg: err.message,
											}, function(ret, err) {

											});
										}
									});

								}
							});
						}
						// callBack(images);
					});
				} else {
					msg("获取相机权限失败!无法打开相机");
				}
			});
		} else if (index == 2) {
			if (api.systemType == "ios") {
				api.showProgress({
					title: '努力压缩中...',
					text: '先喝杯茶...',
					modal: false
				});
				var result = hasPermission('photos'); //权限检测
				var text = '"趣引流"需要使用相册功能,请设置相册权限,点击确定前往设置相册权限,点击取消拒绝';
				requestPermission(text, 'photos', result, function(bool) {
					if (bool) {
						//选择相册
						imgs_Browser($maxLength, $nowLength, function(imgs) {
							if (imgs) {
								for (i in imgs) {
									(function(i) {
										var img_url = imgs[i];
										var imageFilter = api.require('imageFilter');
										imageFilter.getAttr({
											path: img_url,
										}, function(rets, err) {
											if (rets.status) {
												if (rets.width > 800) {
													var widths = 800;
													var heights = 800 / rets.width * rets.height;
													var xwidth = 200;
													var xheight = 200 / rets.width * rets.height;
												} else {
													var widths = rets.width;
													var heights = rets.height;
													var xwidth = 200;
													var xheight = 200 / rets.width * rets.height;
												}
												var timestamp = (new Date()).getTime();
												var demo = api.require('imageOptim');
												demo.compress({
													quality: 0.9,
													width: xwidth,
													height: xheight,
													imgPath: img_url,
													destinationPath: 'fs://' + timestamp + '.png'
												}, function(ret, err) {
													if (ret) {
														api.hideProgress();
														image.push(ret.imgPath);
													} else {
														api.hideProgress();
														api.alert({
															title: '提示',
															msg: err.message,
														}, function(ret, err) {

														});
													}
												});
												demo.compress({
													quality: 0.9,
													width: widths,
													height: heights,
													imgPath: img_url,
													destinationPath: 'fs://' + timestamp + timestamp + '.png'
												}, function(retss, err) {
													if (retss) {
														api.hideProgress();
														images.push(retss.imgPath);
													} else {
														api.hideProgress();
														api.alert({
															title: '提示',
															msg: err.message,
														}, function(ret, err) {

														});
													}
												});

											}
										});
									})(i);
								}
							} else {
								api.hideProgress();
							}
						})
					} else {
						msg("获取相册权限失败!无法打开相册");
						api.hideProgress();
					}
				});
			} else {
				var imageFilter = api.require('imageFilter');
				var result = hasPermission('storage'); //权限检测
				var text = '"趣引流"需要使用相册功能,请设置本地存储权限,点击确定前往设置本地存储权限,点击取消拒绝';
				requestPermission(text, 'storage', result, function(bool) {
					if (bool) {
						//选择相册
						imgs_Browser($maxLength, $nowLength, function(imgs) {
							if (imgs) {
								/* var thumbnailUtil = api.require('thumbnailUtil'); */
								for (i in imgs) {
									(function(i) {
										var img_url = imgs[i];
										var imageFilter = api.require('imageFilter');
										imageFilter.getAttr({
											path: img_url,
										}, function(rets, err) {
											if (rets.status) {
												if (rets.width > 800) {
													var widths = 800;
													var heights = 800 / rets.width * rets.height;
													var xwidth = 200;
													var xheight = 200 / rets.width * rets.height;
												} else {
													var widths = rets.width;
													var heights = rets.height;
													var xwidth = 200;
													var xheight = 200 / rets.width * rets.height;
												}
												var timestamp = (new Date()).getTime();
												var demo = api.require('imageOptim');
												demo.compress({
													quality: 0.9,
													width: xwidth,
													height: xheight,
													imgPath: img_url,
													destinationPath: 'fs://' + timestamp + '.png'
												}, function(ret, err) {
													if (ret) {
														api.hideProgress();
														image.push(ret.imgPath);
													} else {
														api.hideProgress();
														api.alert({
															title: '提示',
															msg: err.message,
														}, function(ret, err) {

														});
													}
												});
												demo.compress({
													quality: 0.9,
													width: rets.width,
													height: rets.height,
													imgPath: img_url,
													destinationPath: 'fs://' + timestamp + timestamp + '.png'
												}, function(retss, err) {
													if (retss) {
														api.hideProgress();
														images.push(retss.imgPath);
													} else {
														api.hideProgress();
														api.alert({
															title: '提示',
															msg: err.message,
														}, function(ret, err) {

														});
													}
												});
											}
										});
									})(i);
								}
							} else {
								api.hideProgress();
							}
							// callBack(images);
						})
					} else {
						msg("获取本地储存权限失败!无法打开相册");
						api.hideProgress();
					}
				});
			}

		}
	});
}

//通过拍照方式返回的图片
function getPicture1(callback) {
	api.getPicture({
		sourceType: 'camera',
		encodingType: 'jpg',
		mediaValue: 'pic',
		destinationType: 'url',
		allowEdit: true,
		quality: 90,
		//  targetWidth:400,
		//  targetHeight:400,
		saveToPhotoAlbum: false
	}, function(ret, err) {
		if (ret) {
			if (ret.data) {
				callback(ret.data);
			}
			//  alert(JSON.stringify(ret));
		}
	});
}

function imgs_Browser($maxLength, $nowLength, callback) {
	var max = $maxLength - $nowLength;
	var UIAlbumBrowser = api.require('UIAlbumBrowser');
	UIAlbumBrowser.open({
		max: max,
		type: 'image',
		styles: {
			bg: '#fff',
			mark: {
				icon: '',
				position: 'bottom_left',
				size: 20
			},
			nav: {
				bg: 'rgba(0,0,0,0.6)',
				titleColor: '#fff',
				titleSize: 18,
				cancelColor: '#fff',
				cancelSize: 16,
				finishColor: '#fff',
				finishSize: 16
			}
		},
		rotation: false
	}, function(ret) {
		if (ret.eventType == 'confirm') {
			var imgs = [];
			if (ret.list.length != 0) {
				for (var i = 0; i < ret.list.length; i++) {
					imgs.push(ret.list[i].path);
				}
				transPath(0, imgs, [], function($imgs) {
					callback($imgs);
				});
			} else {
				callback(imgs);
			}
			// alert(JSON.stringify(ret));
		}
	});

	function transPath($length, $imgs, $arr, callback) {
		for (var i = 0; i < $imgs.length; i++) {
			UIAlbumBrowser.transPath({
				path: $imgs[i]
			}, function(ret, err) {
				if (ret) {
					$arr.push(ret.path);
					if ($arr.length >= $imgs.length) {
						callback($arr);
					}
				}
			});
		}
	}
}
$api

function getNowCity(callBack) { //回调获取当前位置经纬度及街道
	var map = api.require('bMap');
	if (api.systemType == "ios") {
		map.initMapSDK(function(ret) {
			if (ret.status) {
				//检测是否开启定位功能
				var bMap = api.require('bMap');
				bMap.getLocationServices(function(ret, err) {
					// alert(JSON.stringify(ret));
					if (ret.enable) {
						// alert(JSON.stringify(ret));
						bdLoaction();
					} else {
						callBack('', '', '');
					}
				});
			} else {
				//乐生活ios无测试证书，初始化失败，临时处理
				callBack(106.493188, 29.539474, "渝州路");
			}
		});
	} else {
		var bMap = api.require('bMap');
		bMap.getLocationServices(function(ret, err) {
			if (ret.enable) {
				// alert(JSON.stringify(ret));
				bdLoaction();
			} else {
				callBack('', '', '');
			}
		});
	}

	function bdLoaction() { //百度定位
		var map = api.require('bMap');
		map.getLocation({
			accuracy: '10m',
			autoStop: true,
			filter: 1.0
		}, function(ret, err) {
			if (ret.status) {
				// alert(JSON.stringify(ret));
				var map = api.require('bMap');
				var lon = ret.lon;
				var lat = ret.lat;
				map.getNameFromCoords({
					lon: ret.lon,
					lat: ret.lat
				}, function(ret, err) {
					// console.log(JSON.stringify(ret));
					if (ret.status) {
						callBack(lon, lat, ret.streetName);
					}
				});
			} else {
				callBack('', '', '');
				alert(JSON.stringify(err));
			}
		});
	}
}

function loginSuccess(data) {
	var storageList = ['userId', 'userName', 'avatar'];
	storageList.forEach(function(list) {
		if (data[list]) $api.setStorage(list, data[list]);
	});
}

function hasPermission($target) { //检测是否有权限
	var resultList = api.hasPermission({
		list: [$target]
	});
	return resultList;
}

function requestPermission($msg, $target, $result, callBack) { //发起权限请求
	if (api.systemType == "ios") {
		if (!$result[0].granted && !$result[0].undetermined) {
			api.confirm({
				title: '权限设置提醒',
				msg: $msg,
				buttons: ['确定', '取消']
			}, function(ret, err) {
				if (ret.buttonIndex == 1) {
					api.requestPermission({
						list: [$target],
					}, function(ret, err) {});
				} else {
					callBack(false);
				}
			});
		} else if ($result[0].granted) {
			callBack(true);
		} else if (!$result[0].granted && $result[0].undetermined) {
			api.requestPermission({
				list: [$target],
			}, function(ret, err) {
				if (!ret.list[0].granted) {
					callBack(false);
				} else if (ret.list[0].granted) {
					callBack(true);
				}
			});
		}
	} else {
		if (!$result[0].granted) {
			if ($api.getStorage($target + 'Never') == 1) {
				api.confirm({
					title: '权限设置提醒',
					msg: $msg,
					buttons: ['确定', '取消']
				}, function(ret, err) {
					if (ret.buttonIndex == 1) {
						api.requestPermission({
							list: [$target]
						}, function(ret, err) {
							if (!ret.list[0].granted) {
								callBack(false);
							} else if (ret.list[0].granted) {
								callBack(true);
							}
						});
					} else {
						callBack(false);
					}
				});
			} else {
				api.requestPermission({
					list: [$target]
				}, function(ret, err) {
					if (ret.never) {
						$api.setStorage($target + 'Never', 1);
					}
					if (!ret.list[0].granted) {
						callBack(false);
					} else if (ret.list[0].granted) {
						callBack(true);
					}
				});
			}
		} else {
			callBack(true);
		}
	}
}

// 关闭
function closeWin() {
	api.closeWin();
}

function progressAnimate() {
	$(".date").css({
		"display": "none"
	});
	$("#helang-clock").clock();
	setTimeout(function() {
		$("#helang-clock").css({
			"display": "none"
		});
		$("#app").fadeIn(1000);
	}, 2000);
}

function beginAnimation($dom, $time) {
	$('#' + $dom).circleProgress({
		value: 1.0,
		size: 80,
		startAngle: Math.PI / 1.43,
		fill: {
			gradient: ['#ff5353', '#ff8549']
		},
		lineCap: "round",
		emptyFill: "rgba(0, 0, 0, 0)",
		animation: {
			duration: $time
		}
	});
	var timer = null;
	var progressNum = 0;
	timer = setInterval(function() {
		progressNum++;
		$(".public-progress-center p").html(progressNum + "%");
		if (progressNum >= 100) {
			$(".public-progress").fadeOut(1000);
			$("#app").fadeIn(1000);
			clearInterval(timer);
			return;
		}
	}, $time / 100);
}

//苹果手机设备版本查询
function iosVersion($model) {
	if ($model == 'iPhone71') {
		$model = 'iPhone 6';
	}
	if ($model == 'iPhone72') {
		$model = 'iPhone 6 Plus';
	}
	if ($model == 'iPhone81') {
		$model = 'iPhone 6s';
	}
	if ($model == 'iPhone82') {
		$model = 'iPhone 6s Plus';
	}
	if ($model == 'iPhone9,1' || $model == 'iPhone9,3') {
		$model = 'iPhone 7';
	}
	if ($model == 'iPhone9,2' || $model == 'iPhone9,4') {
		$model = 'iPhone 7 Plus';
	}
	if ($model == 'iPhone10,1' || $model == 'iPhone10,4') {
		$model = 'iPhone 8';
	}
	if ($model == 'iPhone10,2' || $model == 'iPhone10,5') {
		$model = 'iPhone 8 Plus';
	}
	if ($model == 'iPhone10,3' || $model == 'iPhone10,6') {
		$model = 'iPhone X';
	}
	return $model;
}

function goFrame($name, $path, $param, $direction, $time, $type) {
	if (!$direction) {
		$direction = "right";
	}
	if (!$time) {
		$time = 300;
	}
	if (!$type) {
		$type = "movein";
	}
	api.openFrame({
		name: $name,
		url: $path,
		reload: true,
		rect: {
			x: 0,
			y: 0,
			w: "auto",
			h: "auto"
		},
		pageParam: $param,
		bgColor: 'rgba(0,0,0,0.0)',
		animation: {
			type: $type,
			subType: "from_" + $direction,
			duration: $time
		},
	});
}

function goWin($name, $path, $pageParam, $direction, $time, $type, $delay) {
	if (!$direction) {
		$direction = "right";
	}
	if (!$time) {
		$time = 200;
	}
	if (!$type) {
		$type = "movein";
	}
	if (!$delay) {
		$delay = 0;
	}
	api.openWin({
		name: $name,
		url: $path,
		pageParam: $pageParam,
		slidBackType: 'edge',
		animation: {
			type: $type,
			subType: "from_" + $direction,
			duration: $time
		},
		delay: $delay
	});
}


function msg(msgs, IntTime) {
	var IntTime = arguments[1] ? arguments[1] : 3000;
	if (msgs) {
		msgs = msgs;
	} else {
		msgs = '网络错误';
	}
	return api.toast({
		msg: msgs,
		duration: IntTime,
		location: 'middle'
	});
}


//发送短信
function send_sms(phone, moban, new_phone, pcmoney, svr) {
	if (new_phone != 0) {
		var ajaxdata = {
			mobile: phone, //发给用户
			moban: moban, //短信模板
			new_phone: new_phone, //新服务者的联系方式
			money: pcmoney, //赔偿金
			svr: svr, //服务者
		}
	} else {
		var ajaxdata = {
			mobile: phone, //发给用户
			moban: moban, //短信模板
			money: pcmoney, //赔偿金
			svr: svr, //服务者
		}
	}
	api.ajax({
		url: server_url + "api_demo/SmsDemo.php",
		method: 'POST',
		data: {
			values: ajaxdata,
		}
	}, function(s, err) {
		if (s.Code == 'OK') {
			return api.toast({
				msg: '已发出短信通知'
			});
		} else {
			return api.toast({
				msg: s.Message
			});
		}
	})
}


// 发送异步请求
function ajPush($url, $values, callBack, $files) {
	var timer;
	var bool = false;
	var num = 0;
	timeout();

	function timeout() {
		setTimeout(function() {
			num++;
			if (num == 10 && bool == false) {
				// callBack("","fail","");
				alert("网络请求超时，请保持网络状况良好，并重新打开APP！");
			} else {
				timeout();
			}
		}, 1000)
	}
	if (!$files) {
		$files = {};
	}
	// console.log(server_api_url+$url);
	// console.log(JSON.stringify($values));
	// console.log(JSON.stringify($files));
	api.ajax({
		url: server_api_url + $url,
		method: 'POST',
		// headers:{'Accept-Language':$api.getStorage('language')},
		data: {
			values: $values,
			files: $files
		}
	}, function(s, err) {
		bool = true;
		if (callBack) {
			return callBack(s, err);
		}
	})
}


// 发送异步请求
function Apiajax($url, $values, callBack, $files) {
	// console.log($url);
	var timer;
	var bool = false;
	var num = 0;
	if (!$files) {
		$files = {};
	}
	// console.log(server_api_url + $url);
	api.ajax({
		url: server_api_url + $url,
		method: 'POST',
		headers: {
			"X-Requested-With": "XMLHttpRequest",
			'M-AppId': api.appId,
			'M-AppToken': $api.getStorage('APP_USER_TOKEN') ? $api.getStorage('APP_USER_TOKEN') : 0
		},
		data: {
			values: $values,
			files: $files
		}
	}, function(s, err) {
		// console.log(JSON.stringify(s));
		// console.log(JSON.stringify(err));
		if (s) {
			if (callBack) {
				callBack(s, err);
			}
		} else {
			if (err) {
				if (err.body) {
					if (typeof err.body == "string") {
						if (err.code == 1) {
							msg("网络请求超时！请检查网络环境是否良好！");
						} else {
							callBack("", err);
						}
						return;
					}
					if (err.body.code == 400) {
						api.closeWin();
						api.confirm({
							title: '登录过期提醒',
							msg: '您的登录已过期，是否前往登录',
							buttons: ['确定', '取消']
						}, function(ret, err) {
							if (ret.buttonIndex == 1) {
								api.openWin({
									name: 'login_win',
									url: 'widget://html/person/login_win.html',
								});
							}
						});
					} else {
						callBack("", err);
					}
				} else {
					callBack("", err);
				}
			}
		}

	})
}

function readAjax($url, callBack) { //全民阅读
	api.ajax({
		url: $url,
		method: 'GET',
	}, function(s, err) {
		if (callBack) {
			return callBack(s, err);
		}
	})
}

//断网监听
function offLine() {
	api.addEventListener({
		name: 'offline'
	}, function(ret, err) {
		alert('糟糕！网络断开了');
	});
}

//沉浸式适配安卓、ios
function setBar($dom) {
	var header = $api.byId($dom);
	var elH = $api.fixStatusBar(header);
	return elH
}

function tabBar($dom) {
	if (api.systemType == "ios") {
		var deviceModel = api.deviceModel;
		deviceModel = iosVersion(deviceModel);
		if (deviceModel == "iPhone X") {
			$api.fixTabBar($api.byId($dom));
		}
	}
}

//计算手机存储空间大小
function getTotalSpace($totalSpace, $arrSpace, callBack) {
	api.getTotalSpace(function(ret, err) {
		// console.log(JSON.stringify(ret));
		if (ret) {
			$totalSpace = parseInt(ret.size / Math.pow(10, 9));
			// console.log($totalSpace);
		}
		for (var i = 0; i < $arrSpace.length; i++) {
			if ($totalSpace <= $arrSpace[i]) {
				// console.log(vm.totalSpace-vm.arrSpace[i-1]);
				// console.log(vm.arrSpace[i]-vm.totalSpace);
				if ($totalSpace < $arrSpace[0]) {
					$totalSpace = $arrSpace[0] + "G";
					return callBack($totalSpace);
				}
				if (($totalSpace - $arrSpace[i - 1]) > ($arrSpace[i] - $totalSpace)) {
					// console.log($totalSpace);
					$totalSpace = $arrSpace[i] + "G";
					return callBack($totalSpace);
				} else {
					$totalSpace = $arrSpace[i - 1] + "G";
					return callBack($totalSpace);
				}
			}
		}
		// console.log(vm.totalSpace);
	});
}

//判断用户是否登录
function isUserId($uid, $path, $param) {
	if (!$api.getStorage($uid)) {
		api.confirm({
			title: '登录验证',
			msg: '您还未登陆，请登陆！',
			buttons: ['确定', '取消']
		}, function(ret, err) {
			if (ret.buttonIndex == 1) {
				api.openWin({
					name: 'login',
					url: $path,
					pageParam: $param,
					reload: true,
					animation: {
						type: "movein", //动画类型（详见动画类型常量）
						subType: "from_right", //动画子类型（详见动画子类型常量）
						duration: 350 //动画过渡时间，默认300毫秒
					}
				});
			}
		});
		return false;
	} else {
		return true;
	}
}

function goPage($name, $path, $y, $b, $param) {
	api.openFrame({
		name: $name,
		url: $path,
		rect: {
			x: 0,
			y: $y,
			w: "auto",
			h: "auto",
			marginBottom: $b
		},
		pageParam: $param,
		bgColor: "rgba(0,0,0,0.3)",
		animation: {
			type: "none",
		},
		reload: true
	});
}

/**
 * 绑定极光推送
 * @param alias string 别名
 * @param tags string|array 标签
 *
 */
function ajpush(alias, tags) {
	var ajpush = api.require('ajpush');
	ajpush.init(function(ret) {
		if (ret && ret.status) { //初始化推送服务，只Android有效，iOS上会自动初始化
			var param = {
				alias: alias,
				tags: [tags]
			}; //绑定
			ajpush.bindAliasAndTags(param, function(ret) {
				var statusCode = ret.statusCode;
				// console.log(statusCode);
			});
		}
	});
}

function NVTabBar(callBack) {
	//基于apicloud模块NVTabBar
	var NVTabBar = api.require('NVTabBar');
	NVTabBar.open({
		styles: {
			bg: '#fff',
			//bg:"widget://image/NVTabBar/tabbar_bg.png",
			h: 58,
			dividingLine: {
				width: 0.5,
				color: '#eee'
			},
			badge: {
				bgColor: '#ff0',
				numColor: '#fff',
				size: 6.0,
				centerX: 40,
				centerY: 6
			}
		},
		items: [{
				w: api.winWidth / 5.0,
				bg: { //（可选项）JSON对象；子项背景配置，若不传则取内部字段默认值
					marginB: -3.0, //（可选项）数字类型；子项背景距离模块底部的距离，设置大于0的数字可实现凸起效果；默认：0
					image: 'rgba(0,0,0,0)', //（可选项）字符串类型；子项的背景，支持rgb、rgba、#、img（仅支持本地图片路径fs://、widget://）；默认：rgba(0,0,0,0)
				},
				iconRect: {
					w: 25.0,
					h: 25.0,
				},
				icon: {
					normal: 'widget://image/public/home1.png',
					// highlight: 'widget://image/home1_1.png',
					selected: 'widget://image/public/home.png'
				},
				title: {
					text: '首页',
					size: 12.0,
					normal: '#4a4a4a',
					selected: '#4193f1',
					marginB: 5.0
				}
			}, {
				w: api.winWidth / 5.0,
				bg: { //（可选项）JSON对象；子项背景配置，若不传则取内部字段默认值
					marginB: -3.0, //（可选项）数字类型；子项背景距离模块底部的距离，设置大于0的数字可实现凸起效果；默认：0
					image: 'rgba(0,0,0,0)', //（可选项）字符串类型；子项的背景，支持rgb、rgba、#、img（仅支持本地图片路径fs://、widget://）；默认：rgba(0,0,0,0)
				},
				iconRect: {
					w: 25.0,
					h: 25.0,
				},
				icon: {
					normal: 'widget://image/public/jiafencenter.png',
					// highlight: 'widget://image/home2_2.png',
					selected: 'widget://image/public/jiafencenter1.png'
				},
				title: {
					text: '加粉中心',
					size: 12.0,
					normal: '#4a4a4a',
					selected: '#4193f1',
					marginB: 5.0
				}
			},
			{
				w: api.winWidth / 5.0,
				bg: { //（可选项）JSON对象；子项背景配置，若不传则取内部字段默认值
					marginB: 6.0, //（可选项）数字类型；子项背景距离模块底部的距离，设置大于0的数字可实现凸起效果；默认：0
					image: 'rgba(0,0,0,0)', //（可选项）字符串类型；子项的背景，支持rgb、rgba、#、img（仅支持本地图片路径fs://、widget://）；默认：rgba(0,0,0,0)
				},
				iconRect: {
					w: 48.0,
					h: 48.0,
				},
				icon: {
					normal: 'widget://image/public/fabu.png',
					//  highlight: 'widget://image/home4.4.png',
					selected: 'widget://image/public/fabu.png'
				},
				title: {
					text: '发布',
					size: 12.0,
					normal: '#4a4a4a',
					selected: '#4193f1',
					marginB: 5.0
				}
			},
			{
				w: api.winWidth / 5.0,
				bg: { //（可选项）JSON对象；子项背景配置，若不传则取内部字段默认值
					marginB: -3.0, //（可选项）数字类型；子项背景距离模块底部的距离，设置大于0的数字可实现凸起效果；默认：0
					image: 'rgba(0,0,0,0)', //（可选项）字符串类型；子项的背景，支持rgb、rgba、#、img（仅支持本地图片路径fs://、widget://）；默认：rgba(0,0,0,0)
				},
				iconRect: {
					w: 25.0,
					h: 25.0,
				},
				icon: {
					normal: 'widget://image/public/woyaozhuanqian.png',
					//  highlight: 'widget://image/home3_s.png',
					selected: 'widget://image/public/woyaozhuanqian1.png'
				},
				title: {
					text: '我要赚钱',
					size: 12.0,
					normal: '#4a4a4a',
					selected: '#4193f1',
					marginB: 5.0
				}
			},
			{
				w: api.winWidth / 5.0,
				bg: { //（可选项）JSON对象；子项背景配置，若不传则取内部字段默认值
					marginB: -3.0, //（可选项）数字类型；子项背景距离模块底部的距离，设置大于0的数字可实现凸起效果；默认：0
					image: 'rgba(0,0,0,0)', //（可选项）字符串类型；子项的背景，支持rgb、rgba、#、img（仅支持本地图片路径fs://、widget://）；默认：rgba(0,0,0,0)
				},
				iconRect: {
					w: 25.0,
					h: 25.0,
				},
				icon: {
					normal: 'widget://image/public/personal.png',
					//  highlight: 'widget://image/home3_s.png',
					selected: 'widget://image/public/personal1.png'
				},
				title: {
					text: '我的',
					size: 12.0,
					normal: '#4a4a4a',
					selected: '#4193f1',
					marginB: 5.0
				}
			}
		],
		selectedIndex: 0
	}, function(ret, err) {
		if (ret.eventType == "click") {
			callBack(ret.index);
		}
		// console.log(JSON.stringify(ret));
	});
}

function getMsgNum(callBack) {
	// console.log($api.getStorage("lwscuserid"));
	ajPush("Miscellaneous/unread_count", {
		userid: $api.getStorage("lwscuserid")
	}, function(s, err) {
		if (s) {
			if (s.status == 1) {
				callBack(s);
			}
		}
		// console.log(JSON.stringify(s));
		// console.log(JSON.stringify(err));
	});
}

//依赖于aui-dialog.js 消息提示
function showDialog(kind, prompt, msg, button, callBack) {
	var dialog = new auiDialog({});
	if (kind == 'alert') {
		showAlert();
	} else {
		showPrompt();
	}

	function showAlert() {
		dialog.alert({
			title: prompt,
			msg: msg,
			buttons: ['取消', button]
		}, function(ret) {
			if (callBack) {
				callBack(ret);
			}
		})
	}

	function showPrompt() {
		dialog.prompt({
			title: prompt,
			text: msg,
			buttons: ['取消', button]
		}, function(ret) {
			if (callBack) {
				callBack(ret);
			}
		})
	}
}

function setStyle() {
	if (api.systemType == "android") {
		api.setStatusBarStyle({
			style: 'light',
			color: 'rgba(0,0,0,0)'
		});
	} else {
		api.setStatusBarStyle({
			style: 'light'
		});
	}
}

// 字符串加密
function post_en(str) {
	var encrypt = new JSEncrypt();
	var publickey =
		'-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDO41DcccJZpytINw/AsHplbl8tJ/EhcZRuinimnxCES+CwXsRnffBDSZ68lVHXiFIopqqKL7G7tMwO8pVMp7qQRbuS5E+SmaOsuZqEa3HP7XRsMW7dXUMlbS2PDkoGR8CY2wE0l8vag1bNHQAHhDDjJHlq0SYyOOEpFJx4Fh6xCQIDAQAB-----END PUBLIC KEY-----'
	encrypt.setPublicKey(publickey);
	var Newstr = encrypt.encrypt(String(str));
	return Newstr;
}


// 图片压缩
function getPicture(method, images) {
	var UIAlbumBrowser = api.require('UIAlbumBrowser');
	api.getPicture({
		sourceType: method,
		encodingType: 'jpg',
		mediaValue: 'pic',
		destinationType: 'url',
		allowEdit: true,
		quality: 100,
		targetWidth: 400,
		targetHeight: 400,
		saveToPhotoAlbum: false
	}, function(ret, err) {
		if (ret.data) {
			if (api.systemType == 'ios') {
				var img_url = ret.data;
				var thumbnailUtil = api.require('thumbnailUtil');
				thumbnailUtil.transform({
					size: {
						w: 400,
						h: 300
					},
					destPath: 'fs://',
					srcPath: img_url,
				}, function(retes, err) {
					images.push(retes.destPath);
				});
			} else {
				var thumbnailUtil = api.require('thumbnailUtil');
				var img_url = ret.data;
				thumbnailUtil.transform({
					size: {
						w: 300,
						h: 400
					},
					destPath: 'fs://',
					srcPath: img_url,
				}, function(retes, err) {
					images.push(retes.destPath);
				});
			}
		} else {
			images = "";
		}
	});
}

function openWebWin(param) {
	var param = {
		name: 'nav',
		url: param.url,
		bgColor: '#fff',
		title: param.title,
		navigationBar: {}
	}
	api.openTabLayout(param);
}

function showProgress(title, text) {
	api.showProgress({
		style: 'default',
		animationType: 'zoom',
		title: title,
		text: text,
		modal: true
	});
}

function hideProgress(timer) {
	setTimeout(function() {
		return api.hideProgress();
	}, timer)
}

// 上传图片(多图或者单图)
// 入参图片地址，多个地址','号隔开;上传模式 单图（type=>1），多图type=>2,win=>winName，frame=> frameName,str=>赋值到vue
// 例(单图)：/storage/emulated/0/Android/data/com.j704833366.ubp/cache/thumbnailUtil/1535104752552.png；
// 例(多图)："/storage/thumbnailUtil/1535104752552.png,/storage/thumbnailUtil/1535104752552.png,/storage/thumbnailUtil/1535104752552.png"；
// return 返回上传过后的地址
function UploadPicter(img, type, name, callback) {
	if (type == 1) {
		api.ajax({
			url: server_api_url + 'Index/UploadErPic',
			method: 'post',
			headers: {
				'M-AppId': api.appId,
				'M-AppToken': $api.getStorage('APP_USER_TOKEN') ? $api.getStorage('APP_USER_TOKEN') : 0
			},
			data: {
				values: {
					name: name
				},
				files: {
					file: img
				}
			}
		}, function(ret, err) {
			if (ret && ret.status == 1) {
				callback(ret.data);
			} else {
				callback(ret.data);
			}
		});
	} else {
		var newArr = "";
		newArr += "{";
		for (var i = 0; i < img.length; i++) {
			newArr += '"file' + i + '":"' + img[i] + '",';
		}
		newArr += "}";
		setTimeout(function() {
			api.ajax({
				url: server_api_url + 'Index/UploadErPic',
				method: 'post',
				headers: {
					'M-AppId': api.appId,
					'M-AppToken': $api.getStorage('APP_USER_TOKEN') ? $api.getStorage('APP_USER_TOKEN') : 0
				},
				data: {
					values: {
						name: name
					},
					files: eval('(' + newArr + ')')
				}
			}, function(ret, err) {
				if (ret && ret.status == 1) {
					callback(ret.data);
				} else {
					callback(ret.data);
				}
			});
		}, 500)
	}
}

function getMsgNum(callBack) {
	// console.log(JSON.stringify({
	// 	users_id:$api.getStorage('uid'),
	// }));
	if ($api.getStorage('token')) {
		Apiajax("Smallfunction/unread_msg", {
			users_id: $api.getStorage('token'),
		}, function(s, err) {
			if (s) {
				if (s.status == 1) {
					callBack(s.count);
				}
			}
			// console.log(JSON.stringify(s));
			// console.log(JSON.stringify(err));
		})
	} else {
		callBack(0);
	}

}
//获取城市
function getCity(lon, lat, callBack) {
	var map = api.require('bMap');
	map.getNameFromCoords({
		lon: lon,
		lat: lat
	}, function(ret, err) {
		if (ret.status) {
			$api.setStorage('city_text', ret.district);
			callBack();
		}
	});
}

function gomsg() {
	if (!$api.getStorage('token')) {
		goWin("login", "../person/login.html", {});
		return;
	}
	goWin("msgcenter", "../person/msgcenter.html", {});
}

function share() {
	goFrame("share", "../person/share/share.html", {}, "", "", "none");
}
//控制台警告:Using unescaped '#' characters in a data URI body is deprecated and will be removed in M67, around May 2018. Please use '%23' instead. See https://www.chromestatus.com/features/5656049583390720 for more details. at JsRuntime : 0
//原因1：openFrameGroup中的子fram路径出错或找不到子fram;


// 张功睿的辅助函数模块
var zgr = (function() {

	/**
	 * @description: 跳转到登录页面
	 * @param {number} _name 执行该函数的窗口名
	 * @return:
	 */
	var goLogin = function(_name) {
		var options = {
			name: 'login',
			url: 'widget://html/person/login.html',
			bounces: false,
			pageParam: {
				name: _name
			}
		}
		api.openWin(options)
	}

	/**
	 * @description: 监听右划事件和点击返回键事件
	 * @param {function} _callback 回调函数
	 * @return:
	 */
	var addBackEventListener = function(_callback) {
		api.addEventListener({
			name: 'swiperight'
		}, function(ret, err) {
			_callback()
		});
		api.addEventListener({
			name: 'keyback'
		}, function(ret, err) {
			_callback()
		});
	}

	/**
	 * @description: window 监听返回键
	 * @param {boolean} _isFrame 是否是 frame
	 * @return:
	 */
	var winKeyback = function(_isFrame) {
		var option = {
			name: 'keyback'
		}

		if (_isFrame) {
			api.addEventListener(option, function(ret, err) {
				api.closeFrame({
					name: 'share'
				});
			})
			setTimeout(function() {
				zgr.winKeyback(false)
			}, 1000)
		} else {
			api.addEventListener(option, function(ret, err) {
				if (vm.close) {
					vm.close()
				} else if (qhSelect) {
					qhSelect(0)
				} else {
					api.closeWin()
				}
			})
		}
	}

	/**
	 * @description: frame 执行 window 函数，与 winKeyback 配套使用
	 * @param {type}
	 * @return:
	 */
	var frameExec = function() {
		api.execScript({
			name: api.winName,
			script: 'zgr.winKeyback(' + true + ')'
		});
	}

	return {
		goLogin: goLogin,
		addBackEventListener: addBackEventListener,
		winKeyback: winKeyback,
		frameExec: frameExec
	}
})()


//田迅最新封装db模块
/**
 * @description: 基于db模块的二次封装,如果未添加db模块请登录https://docs.apicloud.com/Client-API/Func-Ext/db
 * @param {$method,$obj}参数一：执行指令<0>初始化'init'or'INIT'返回引用数据类型<1>获取'get' or 'GET';<2>添加'add' or 'ADD';<3>清空'clear' or 'CLEAR'; 参数二:需要添加的对象如果是执行参数一中的执行<2>必传
 * @return:{status:bool}
 */
function db_CURD($method, $obj) {
	var db = api.require('db');

	if ($method == 'get' || $method == 'GET') {
		return db_queryResult();
	} else if ($method == 'add' || $method == 'ADD') {
		var result = db_select();
		var results = db_queryResult();
		var arr = results.data;
		if (result.data.length == 0 && arr.length == 0) {
			return db_insert($obj);
		} else {
			if (arr.length == 1 && arr[0].id == $obj.id) {
				return {
					status: true
				};
			}
			var ret = db_empty();
			for (var i = 0; i < arr.length; i++) {
				if (arr[i].id == $obj.id) {
					arr.splice(i, 1);
					break;
				}
			}
			if (arr.length > 5) {
				arr.splice((arr.length - 1), 1);
			}
			arr.unshift($obj);
			return db_insert_arr(arr);
		}
	} else if ($method == 'clear' || $method == 'CLEAR') {
		var ret = db_empty();
		return ret;
	} else if ($method == 'init' || $method == 'INIT') {
		return db_init();
	} else {
		alert("Oh FUCK! ARE YOU PIG ?");
		return {
			status: true
		};
	}

	function db_init() {
		var db = api.require('db');
		var arr = [];
		var leshenghuo = db.openDatabaseSync({
			name: 'leshenghuo',
			path: api.fsDir + '/data/download.db'
		});
		var search = db.selectSqlSync({
			name: 'leshenghuo',
			sql: 'select * from sqlite_master where name = "search"'
		});
		// console.log(search);不存在则创建表,存在则查询
		//创建数据库 business_id店铺id  type跳转标识 name店铺名称 picture店铺封面图
		if (search.data.length == 0) {
			db.executeSqlSync({
				name: 'leshenghuo',
				sql: 'CREATE TABLE search(id int,business_id int,type int,name varchar(100),picture varchar(100))'
			});
		} else {
			var ret = db_CURD("get");
			arr = ret.data;
		}
		return arr;
	}

	function db_queryResult() {
		var ret = db.selectSqlSync({
			name: 'leshenghuo',
			sql: 'SELECT * FROM search '
		});
		return ret;
	}

	function db_select() {
		var ret = db.selectSqlSync({
			name: 'leshenghuo',
			sql: 'SELECT * FROM search WHERE id = ' + $obj.id
		});
		return ret;
	}

	function db_insert(obj) {
		if (obj) {
			var ret = db.executeSqlSync({
				name: 'leshenghuo',
				sql: 'INSERT INTO search values(' + obj.id + ',' + obj.business_id + ',' + obj.type + ',"' + obj.name + '","' +
					obj.picture + '")'
			});
			return ret;
		} else {
			alert("Oh FUCK! ARE YOU PIG ?");
			return {
				status: true
			}
		}
	}

	function db_update($id, obj) {
		if (obj) {
			var ret = db.executeSqlSync({
				name: 'leshenghuo',
				sql: 'UPDATE search SET id=' + obj.id + ',business_id=' + obj.business_id + ',type=' + obj.type + ',name="' + obj
					.name + '",picture="' + obj.picture + '" WHERE id =' + $id + ' '
			});
			return ret;
		} else {
			alert("Oh FUCK! ARE YOU PIG ?");
			return {
				status: true
			}
		}
	}

	function db_empty() {
		var ret = db.executeSqlSync({
			name: 'leshenghuo',
			sql: 'DELETE FROM search'
		});
		return ret;
	}

	function db_insert_arr(arrList) {
		for (var i = 0; i < arrList.length; i++) {
			db.executeSqlSync({
				name: 'leshenghuo',
				sql: 'INSERT INTO search values(' + arrList[i].id + ',' + arrList[i].business_id + ',' + arrList[i].type + ',"' +
					arrList[i].name + '","' + arrList[i].picture + '")'
			});
		}
		return {
			status: true
		};
	}

}
